<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//会计记账管理
class Cash extends CommonController {

	function __construct(){
		
		parent::__construct();
		$this->load->model('Accounting/accountingModel','CurModel');
		$this->load->model('Accounting/TeamAccountingModel','TeamModel');
		$this->load->model('Accounting/AccountingBalanceModel','BalanceModel');
	}
	
	
	//start
	/**
	* @name 获取列表
	* @param page ture char 页面
	* @param size ture char 数量
	* @return 成功返回1
	*/
	//end
	function get_list(){
		$user_id = $this->user_id;
		
		
		if(!$this->check_priv('accounting_duizhang|accounting_duizhang_1')){
			$this->err_out(LANG_NOPRIV);
		}


		$page = $this->input->post('page',null,1);
		$size = $this->input->post('size',null,10);
		
		$filter = $this->input->post('f',null,array());

		
		if(empty($filter['start_date_month'])){
			$this->err_out('请选择月份');
		}
		else{
			$filter['start'] = date('Y-m-d',strtotime($filter['start_date_month'].'-01'));
		}

		//截止日期
		if(!empty($filter['end_date_month'])){
			$filter['end'] = date('Y-m-d',strtotime($filter['end_date_month'].'-01 +1 month -1 day'));
		}else{
			$filter['end'] = date('Y-m-d');
		}
		

		$info = array();
		
		$info['balance_status'] = 0;
		$current_month = date('Y-m',strtotime($filter['date_month'].'-01'));
		$is_exist = $this->BalanceModel->_where_exist(array('date_month'=>$current_month,'status'=>0));
		if($is_exist){
			$info['balance_status'] = 1;
		}
		
		
		$total_before = 0;
		
		
		// $prev = $this->BalanceModel->get_prev_balance($filter['date_month']);
		// if($prev){
		// 	$total_before = $prev['money'];
		// }
		// else{
		// 	$total_before = 0;
		// }
		
		
		$arr = $filter;
		unset($arr['date_month']);
		$cash_res = $this->CurModel->get_list($arr,$page,$size);
		
		$cash_list = $cash_res['list'];
		$info['count'] = $cash_res['count'];
		$this->load->model('User/UserModel','UserModel');
		$this->load->model('User/SubjectModel','SubjectModel');//为了取出科目码, ling添加
		
		foreach($cash_list as $key=>$val){
			$cash_list[$key]['month'] = date('m',strtotime($val['date']));
			$cash_list[$key]['day'] = date('d',strtotime($val['date']));
			

			

			
			if($val['mtype']==0){
				$cash_list[$key]['income_s'] = $val['money'];
				$cash_list[$key]['expenses_s'] = '-';
			}
			else{
				$cash_list[$key]['income_s'] = '-';
				$cash_list[$key]['expenses_s'] = $val['money'];
			}
			
			$cash_list[$key]['username'] = '未知';
			$ls_user = $this->UserModel->get_user($val['user_id']);
			if($ls_user){
				$cash_list[$key]['username'] = $ls_user['nickname'];
			}
			
			//通过科目名称取科目码,ling添加
			$subject_name = $this->SubjectModel->get_subject($val['subject']);
			if($subject_name){
				//$cash_list[$key]['subject'] = "(".$subject_name['code'].")".$cash_list[$key]['subject'];
				$cash_list[$key]['subject_code'] = $subject_name['code'];
			}
			
		}
		$info['list'] = $cash_list;
		

		
		$this->data_out($info);
	}
	
	
	//start
	/**
	* @name 获取信息
	* @param id ture char ID
	* @return 成功返回1
	*/
	//end
	function get_info(){
		$user_id = $this->user_id;
		
		$result = parent::_get_info();
		if(!$result){
			$this->err_out($this->getError());
		}
		
		$this->data_out($result);
	}
	
	
	//start
	/**
	* @name 更新或添加数据
	* @param date_month ture int 月份
	* @param company_id ture int 公司ID
	* @return 成功返回1
	*/
	//end
	function save(){
		$user_id = $this->user_id;
		if(!$this->check_priv('accounting_duizhang_2')){
			$this->err_out(LANG_NOPRIV);
		}
		
		$filter = array(
			'date_month'=>'月份不能为空',
			'region'=>'地区不能为空',
			'date'=>'日期不能为空',
			//'bumen'=>'部门不能为空',
			'subject'=>'科目不能为空',
			'bz'=>'币种不能为空',
			'mtype'=>'类型不能为空',
			'company'=>'公司主体不能为空',
			'money'=>array(
				'required'=>'金额不能为空',
				//'regex_match[/^[0-9]*$/]'=>'请输入正确的金额'
				'regex_match[/^(d*.d{0,2}|d+).*$/]'=>'请输入正确的金额'
			),
			'type'=>'请设置类型',
			'info'=>'请填写摘要'
		);
		$post = array('date_month','region','date','bumen','subject','date','bz','mtype','company','money','type','bumen_scale','info');
		$farr = array(
			'post'=>$post,
			'filter'=>$filter
		);
		$time = time();
		$date_month = $this->input->post('date_month');
		$bz = $this->input->post('bz');
		$mtype = $this->input->post('mtype');
		$money = $this->input->post('money');
		$id = $this->input->post('id',null,0);

		//这里判断部门是否有空的,空的去掉
		$bumen = explode(',',$this->input->post('bumen'));
		$bumen_scale = explode(',',$this->input->post('bumen_scale'));
		if(count($bumen) > 1){
			foreach($bumen as $k=>$v){
				if($v == ''){
					unset($bumen[$k]);
					$bumen_scale[0] += $bumen_scale[$k];
					unset($bumen_scale[$k]);
				}
			}
			$_POST['bumen'] = implode(',', $bumen);
			$_POST['bumen_scale'] = implode(',', $bumen_scale);
		}
		
		$income = '';
		$expenses = '';
		
		if($bz == '人民币'){
			$bs = 1;
		}else{
			$this->load->model('User/CurrencyModel','CurrencyModel');
			$curr = $this->CurrencyModel->bz_get_info($bz);
			$bs = $curr?$curr['exchange_rate']:1;
		}
		
		if($mtype==0){
			$income = toFloat($money / $bs);
		}
		else{
			$expenses = toFloat($money / $bs);
		}
		$balance = $this->get_balance($date_month,$id);
		$balance += $income;
		$balance -= $expenses;
		
		if(empty($id)){
			$certificate = $this->get_certificate($this->input->post());
			if(!$certificate){
				$this->err_out('生成凭证号码错误，参数缺失');
			}
			$arr = array(
				'addtime'=>$time,
				'certificate'=>$certificate,
				'user_id'=>$user_id
			);
		}
		else{
			$arr = array();
			
		}
		
		//$result = $this->CurModel->get_info($id);
		$arr['income'] = $income;
		$arr['expenses'] = $expenses;
		$arr['balance'] = $balance;

		$result = parent::_save($farr,$arr,true);
		if(!$result){
			$this->err_out($this->getError());
		}else{
			//只有在修改时才会去同步,需要同步到现金日记账或者银行日记账中
			if($result['type'] < 2 && !empty($id)){
				$result['certificate'] = $this->input->post('certificate');
				
				$certificate = $result['certificate'];
				$res = $result;
				unset($res['certificate']);
				unset($res['id']);
				$this->CurModel->synchro_cash($certificate, $res);
			}

			//同步到团队陨益表
			$res2 = $result;
			unset($res2['id']);
			if(!empty($id)){//修改
				$certificate = $this->input->post('certificate');
				$this->TeamModel->synchro_team($res2, $certificate);
			}else{//添加
				$this->TeamModel->synchro_team($res2, '');
			}

		}
		
		$this->add_log("保存记账信息【{$result['id']}】",'accounting');
		
		$this->data_out($result);
	}
	
	//获取凭证
	function get_certificate($info){
		
		if(!isset($info['region']) || !isset($info['type']) || !isset($info['date_month'])){
			return false;
		}
		$txt = '';
		$this->load->dmodel('regions','regions');
		$region = $this->regions->getRow("name='{$info['region']}'");
		
		if($region){
			$txt .= $region['sx_name'];
		}
		if(!in_array($info['type'],array(0,1))){
			$info['type'] = 2;
		}
		
		$arr = array('C','B','O');
		$txt .= $arr[$info['type']];
		
		$txt .= str_replace('-','',$info['date_month']);
		$arr = array('date_month'=>$info['date_month'],'type'=>$info['type']);
		$num = $this->CurModel->getCount($arr)+1;
		
		$txt .= str_pad($num,4,"0",STR_PAD_LEFT);
		
		return $txt;
	}
	
	function get_balance($date_month,$id=''){
		
		$prev = $this->BalanceModel->get_prev_balance($date_month);
		if($prev){
			$prev_money = $prev['money'];
		}
		else{
			$prev_money = 0;
		}

		$arr = $id?array('date_month'=>$date_month,'currentID'=>$id):array('date_month'=>$date_month);
		
		$income = $this->CurModel->get_totals($arr,'income');
		$expenses = $this->CurModel->get_totals($arr,'expenses');
		
		$money = $prev_money + $income - $expenses;
		
		return $money;
	}
	//start
	/**
	* @name 删除
	* @param id ture int ID
	* @return 成功返回1
	*/
	//end
	function del(){
		
		if(!$this->check_priv('accounting_duizhang_2')){
			$this->err_out(LANG_NOPRIV);
		}
		
		//$result = parent::_del();
		$id = $this->input->post('id',null,0);
		$info = $this->CurModel->get_info($id);
		if(!$info){
			$this->err_out('数据不存在');
		}

		$result = $this->CurModel->edit(array('is_del'=>1),"id='{$id}'");
		if(!$result){
			$this->err_out($this->getError());
		}
		
		//同步到团队损益表里
		$this->TeamModel->synchro_team(array('is_del'=>1),$info['certificate']);

		$this->add_log("删除数据【{$result}】信息",'accounting');
		$this->data_out($result);
		
	}
	
	
	//start
	/**
	* @name 批量操作
	* @param ids ture int_array ID组合
	* @param act ture int 操作类型enable，disconnected，delete
	* @return 成功返回1
	*/
	//end
	function batch_act(){
		if(!$this->check_priv('accounting_duizhang_2')){
			$this->err_out(LANG_NOPRIV);
		}
		
		$user_id = $this->user_id;
		$ids = $this->input->post('ids',null,array());
		$act = $this->input->post('act',null,'');
		
		$act_arr = array('compare','qcompare','delete');
		if(!in_array($act,$act_arr)){
			$this->err_out('错误的错误');
		}
		if(!is_array($ids)){
			$ids = explode(',',$ids);
		}
		if(count($ids)<=0){
			$this->err_out('请选择成员');
		}
		$ls_ids = array();
		foreach($ids as $id){
			if(!empty($id)){
				$ls_ids[] = $id;
			}
		}

		$team_where = array();
		if($act=='compare'){
			$team_where = array('status'=>1);
			$this->CurModel->edit(array('status'=>1),"id in(".implode(',',$ls_ids).")");
			
			$this->load->model('System/Msg_templateModel','Msg_templateModel');//通知处理钩子
			$this->Msg_templateModel->notice_handle($user_id,'duizhang');
		}
		elseif($act=='qcompare'){
			$team_where = array('status'=>0);
			$this->CurModel->edit(array('status'=>0),"id in(".implode(',',$ls_ids).")");
		}
		elseif($act=='delete'){
			//$this->CurModel->del("id in(".implode(',',$ls_ids).")");
			$this->CurModel->edit(array('is_del'=>1),"id in(".implode(',',$ls_ids).")");
		}

		//同步团队损益表
		$this->TeamModel->batch_team($team_where, $ls_ids);
		
		$this->add_log("执行【{$act}】批量操作【".implode(',',$ls_ids)."】信息",'accounting');
		
		$this->data_out(1);
	}
	
	//start
	/**
	* @name 引入记账
	* @param date ture char 日期开始和结束
	* @return 成功返回1
	*/
	//end
	function yinru(){
		
		if(!$this->check_priv('accounting_duizhang_2')){
			$this->err_out(LANG_NOPRIV);
		}
		
		
		$filter = $this->input->post('f',null,array());
		if(empty($filter['date'])){
			$this->err_out('请选择日期范围');
		}
		
		$fg = explode('|',$filter['date']);
		if(count($fg)<2){
			$this->err_out('错误的日期时间');
		}
		$start = $fg[0];
		$end = $fg[1];
		
		$farr = array('type','region','company','bumen','subject');
		$arr = array();
		foreach($filter as $key=>$val){
			if(in_array($key,$farr)){
				$arr[$key] = $val;
			}
		}
		
		$arr['start'] = $start;
		$arr['end'] = $end;
		
		
		$result = $this->CurModel->yinru_data($arr);
		if(!$result){
			$this->err_out('引入数据错误');
		}
		
		$this->add_log("引入【{$filter['date']}】记账信息",'accounting');
		
		$this->data_out(1);
		
	}
	
	
	//start
	/**
	* @name 设置是否对账
	* @param id ture int ID
	* @param status ture int 状态
	* @return 成功返回1
	*/
	//end
	function set_ok(){
		if(!$this->check_priv('accounting_duizhang_2')){
			$this->err_out(LANG_NOPRIV);
		}
		
		$id = $this->input->post('id',null,0);
		$status = $this->input->post('status',null,0);
		$info = $this->CurModel->get_info($id);
		if(!$info){
			$this->err_out('数据不存在');
		}
		
		$this->CurModel->edit(array('status'=>$status),"id ='{$id}'");

		//同步团队损益表去 w_team_accounting
		$this->TeamModel->synchro_team(array('status'=>$status),$info['certificate']);
		
		$this->add_log("设置【{$id}】对账状态为{$status}",'accounting');
		
		$this->data_out(1);
	}
	
	
	//start
	/**
	* @name 导入数据
	* @param mark ture char 文件标记
	* @return 成功返回1
	*/
	//end
	function import_data(){
		if(!$this->check_priv('accounting_duizhang_2')){
			$this->err_out(LANG_NOPRIV);
		}
		
		$user_id = $this->user_id;
		
		$mark = $this->input->post('mark',null,'');
		$type = $this->input->post('type',null,0);
		$current_month = $this->input->post('date_month',null,date('Y-m'));
		
		
		$this->load->dmodel('upload_data','upload_data');
		
		$this->load->model('User/companyModel','companyModel');
		
		$info = $this->upload_data->_field_get_info($mark,'token');
		if(!$info){
			$this->err_out('文件不存在');
		}
		
		$file_path = FCPATH .'upload/'.$info['path'];
		if(!file_exists($file_path)){
			$this->err_out('文件路径不存在');
		}
		
		
		
		
		$this->load->library('PHPExcel');
		
		$fileType = PHPExcel_IOFactory::identify($file_path);
		$objReader = PHPExcel_IOFactory::createReader($fileType);
		$objPHPExcel = $objReader->load($file_path);
		$currentSheet = $objPHPExcel->getSheet(0);
		
		$highestRow = $currentSheet->getHighestRow(); // 取得总行数
		$highestColumm = $currentSheet->getHighestColumn(); // 取得总列数

		//把Excel数据保存数组中
		$data = array();
		for ($rowIndex = 1; $rowIndex <= $highestRow; $rowIndex++) {        //循环读取每个单元格的内容。注意行从1开始，列从A开始
			for ($colIndex = 'A'; $colIndex <= $highestColumm; $colIndex++) {
				$addr = $colIndex . $rowIndex;
				$cell = $currentSheet->getCell($addr)->getValue();
				if ($cell instanceof PHPExcel_RichText) { //富文本转换字符串
					$cell = $cell->__toString();
				}
				$data[$rowIndex][$colIndex] = $cell;
			}
		}
		
		
		$this->load->model('User/CurrencyModel','CurrencyModel');
		
		
		foreach($data as $row=>$col){
			if($row<=2){
				continue;
			}
			
			$date = trim($col['A']);
			
			$date = date('Y-m-d',strtotime($date));
			if($date<'2000-01-01'){
				continue;
			}
			$date_month = date('Y-m',strtotime($date));
			if($date_month != $current_month){
				continue;
			}
			$region = trim($col['B']);
			$company = trim($col['C']);
			$bumen = trim($col['D']);
			$bumen_scale =trim( $col['E']);
			$subject = trim($col['F']);
			$info = trim($col['G']);
			$bz = trim($col['H']);
			$mtype = trim($col['I'])=='收入'?1:0;
			$money = trim($col['J']);
			
			$bumen_fg = explode(',',$bumen);
			$scale_fg = explode(',',$bumen_scale);
			$ls_scale = array();
			foreach($bumen_fg as $key=>$val){
				$ls_scale[] = isset($scale_fg[$key])?$scale_fg[$key]:0;
			}
			$bumen_scale = implode(',',$ls_scale);
			
			$income = '';
			$expenses = '';
			if($bz == '人民币'){
				$bs = 1;
			}else{
				$curr = $this->CurrencyModel->bz_get_info($bz);
				$bs = $curr?$curr['exchange_rate']:1;
			}
			
			if($mtype==0){
				$income = toFloat($money / $bs);
			}
			else{
				$expenses = toFloat($money / $bs);
			}
			
			$balance = $this->get_balance($date_month);
			$balance += $income;
			$balance -= $expenses;
			
			
			$ls_arr = array(
				'date'=>$date,
				'date_month'=>$date_month,
				'region'=>$region,
				'company'=>$company,
				'bumen'=>$bumen,
				'bumen_scale'=>$bumen_scale,
				'subject'=>$subject,
				'info'=>$info,
				'bz'=>$bz,
				'mtype'=>$mtype,
				'money'=>$money,
				'income'=>$income,
				'expenses'=>$expenses,
				'type'=>$type,
				'user_id'=>$user_id,
				'balance'=>$balance,
				'addtime'=>time()
			);
			
			$ls_arr['certificate'] = $this->get_certificate($ls_arr);
			if(!$ls_arr['certificate']){
				continue;
			}
			$this->CurModel->add($ls_arr);

			//同步团队损益表
			$this->TeamModel->add($ls_arr);
			
		}
		
		$this->add_log("导入账目",'accounting');
		$this->data_out(1);
	}
	
	
}
